var allQrcodesListsImage = [];
var linkTotalData = {};
var linkDetialLoad = { "qrcode": 1, "chart": 1, "record": 1, "other": 1 };
var nextRecordData = { "total": "", "total_end": "", "total_start": "" };
var $table = $('#qrcodeImage');
var $tableRecord = $("#recode-lists");
var linkQrcodes = [];
var linkRecordLists = [];
var miniQrcode = "";
var imagearr = [];

$(document).ready(function() {
    $("#country_lists li").click(function() {
        $("#country_lists li").removeClass("active");
        $(this).addClass("active");
        var country = $(this).attr('country');
        $("#platfrom_typeul li").removeClass("active");
        $("#platfrom_typeul_1").show().addClass("active");
        $("#platfrom_typeul_8").hide();
        $("#platfrom").val(1);
        $("#platfrom_notice").html("<b>推广提示：</b>适用于其他推广场景推广！");
        $(".platfrom_typeul_self").remove();
        if (country == 1) {
            $("#country_notice").html("<b>地区提示：</b>链接在国内访问会提供访问加速。");
            $("#country_detial_row label").html('<b>*</b>选择获取链接类型：<font>除特殊场景外选择通用即可</font>');
            $("#platfrom_typeul_2").show();
            $("#platfrom_typeul_3").show();
            $("#platfrom_typeul_4").show();
            $("#platfrom_typeul_5").show();
            $("#platfrom_typeul_6").show();
            $("#platfrom_typeul_7").show();
            $("#platfrom_typeul_9").show();
            $("#country_detial_row").show();
        } else if (country == 2) {
            $("#country_notice").html("<b>地区提示：</b>链接在国外访问会提供访问加速。");
            $("#country_detial_row label").html('<b>*</b>选择获取链接类型：<font>除特殊场景外选择通用即可</font>');
            $("#country_detial_row").hide();
            $("#platfrom_typeul_2").hide();
            $("#platfrom_typeul_3").hide();
            $("#platfrom_typeul_4").hide();
            $("#platfrom_typeul_5").hide();
            $("#platfrom_typeul_6").hide();
            $("#platfrom_typeul_7").hide();
            $("#platfrom_typeul_9").hide();
        } else if (country == 3) {
            $("#country_notice").html("<b>地区提示：</b>链接支持全球访问,但不提供加速!");
            $("#country_detial_row label").html('<b>*</b>选择获取链接类型：<font>除特殊场景外选择通用即可</font>');
            $("#platfrom_typeul_2").hide();
            $("#platfrom_typeul_3").hide();
            $("#platfrom_typeul_4").hide();
            $("#platfrom_typeul_5").show();
            $("#platfrom_typeul_6").hide();
            $("#platfrom_typeul_7").hide();
            $("#platfrom_typeul_9").show();
        } else {
            $("#country_notice").html("<b>地区提示：</b>使用自有域名访问,但不提供加速!");
            $("#country_detial_row label").html('<b>*</b>选择自有域名：');
            $("#platfrom_typeul li").hide();
            $("#country_detial_row").show();
            userDomainList();
        }
        $("#country").val(country);
    });

    $(document).on("click","#platfrom_typeul li",function () {
        var id = $(this).attr("id");
        if(id == "platfrom_typeul_self"){
            $("#platfrom_typeul li").removeClass("active");
            $(this).addClass("active");
            $("#platfrom").val($(this).text());
        }
    });

    $("#platfrom_typeul li").click(function() {
        $("#platfrom_typeul li").removeClass("active");
        $(this).addClass("active");
        var platfrom = $(this).attr('platfrom');
        if (platfrom == 1) {
            $("#platfrom_notice").html("<b>推广提示：</b>适用于其他推广场景推广！");
            $("#platfrom_help_dy").hide();
            $("#platfrom_help_dx").hide();
            $("#platfrom_help_bd").hide();
            $("#platfrom_help_other").show();
        } else if (platfrom == 2) {
            $("#platfrom_notice").html("<b>推广提示：</b>抖音视频播放流量大，使用本链接可以精确统计数据!");
            $("#platfrom_help_dy").show();
            $("#platfrom_help_dx").hide();
            $("#platfrom_help_bd").hide();
            $("#platfrom_help_other").hide();
        } else if (platfrom == 3) {
            $("#platfrom_notice").html("<b>推广提示：</b>腾讯广点通投放广告使用，针对微信环境进行优化！");
            $("#platfrom_help_dy").hide();
            $("#platfrom_help_dx").hide();
            $("#platfrom_help_bd").hide();
            $("#platfrom_help_other").hide();
        } else if (platfrom == 4) {
            $("#platfrom_notice").html("<b>推广提示：</b>微博白名单域名，跳转无拦截提醒！");
            $("#platfrom_help_dy").hide();
            $("#platfrom_help_dx").hide();
            $("#platfrom_help_bd").hide();
            $("#platfrom_help_other").hide();
        } else if (platfrom == 5) {
            $("#platfrom_notice").html("<b>推广提示：</b>支持短链接，节省推广成本！");
            $("#platfrom_help_dy").hide();
            $("#platfrom_help_dx").show();
            $("#platfrom_help_bd").hide();
            $("#platfrom_help_other").hide();
        } else if (platfrom == 6) {
            $("#platfrom_notice").html("<b>推广提示：</b>百度推广支持百度APP直接跳转微信！");
            $("#platfrom_help_dy").hide();
            $("#platfrom_help_dx").hide();
            $("#platfrom_help_bd").show();
            $("#platfrom_help_other").hide();
        } else if (platfrom == 7) {
            $("#platfrom_notice").html("<b>推广提示：</b>微信群内分享容易封域名，我们会随时切换链接！");
            $("#platfrom_help_dy").hide();
            $("#platfrom_help_dx").hide();
            $("#platfrom_help_bd").hide();
            $("#platfrom_help_other").hide();
        } else if (platfrom == 9) {
            $('#qudaoModal').modal('hide');
            $("#platfrom_typeul li").removeClass("active");
            $("#platfrom_typeul li[platfrom=1]").addClass("active");
            var links_id = $("#links_id").val();
            window.open("/admin/tool/card_add?links_id="+links_id+"&link_type=wx");
            return;
        } else {
            return;
        }
        $("#platfrom").val(platfrom);
    });

    $("#linkDetialTable li").click(function() {
        $("#linkDetialTable li").removeClass("active");
        $(this).addClass("active");
        var value = $(this).attr('data');
        $(".data-qrcode").hide();
        $(".data-chart").hide();
        $(".data-record").hide();
        $(".data-other").hide();
        $(".data-total").hide();
        $(".data-" + value).show();
        if (value == "qrcode") {
            if (linkDetialLoad.qrcode >= 3) {
                return;
            }
            linkDetialLoad.qrcode = 2;
            qrcodeListReload();
        } else if (value == "chart") {
            qrcodesListsData(1);
        } else if (value == "total") {
            getTotalChart();
        } else if (value == "record") {
            if (linkDetialLoad.record >= 3) {
                return;
            }
            linkDetialLoad.record = 2;
            linkQrcodeAll(1);
        } else if (value == "other") {
            if (linkDetialLoad.other >= 2) {
                return;
            }
            linkDetialLoad.other = 2;
            renderOtherData("thismonth");
        }
    });

    $("#moreDataUl li").click(function() {
        $("#moreDataUl li").removeClass("active");
        $(this).addClass("active");
        var value = $(this).attr('data');
        var name = $(this).text();
        $("#moreDataUl_bd").hide();
        $("#moreDataUl_uc").hide();
        $("#moreDataUl_ks").hide();
        $("#moreDataUl_gdt").hide();
        $("#moreDataUl_qrcode").hide();
        $("#moreDataUl_api").hide();
        $("#moreDataUl_" + value).show();
        $("#moreDataTitle label").text(name + "参数获取:");
        if (value == "bd") {
            $("#moreDataTitle div").html("可接入百度基木鱼实现点击/加载直接拉起小程序");
            $("#moreDataNotice div").html("参数 <font class='text-warning'>有效期1年</font> 过期需复制新的更换；如<font class='text-warning'>更换小程序</font> 后必须在基木鱼后台更换下方参数。");
            $("#moreDataNotice").show();
        } else if (value == "uc") {
            $("#moreDataTitle div").html("实现UC锦帆制造一键拉起小程序微信小程序展示二维码");
            $("#moreDataNotice div").html("参数 <font class='text-warning'>有效期1年</font> 过期需复制新的更换；如<font class='text-warning'>更换小程序</font> 后必须在锦帆制造后台更换下方参数。");
            $("#moreDataNotice").show();
        } else if (value == "ks") {
            $("#moreDataTitle div").html("实现快手磁力建站一键拉起小程序微信小程序展示二维码");
            $("#moreDataNotice div").html("参数 <font class='text-warning'>有效期1年</font> 过期需复制新的更换；如<font class='text-warning'>更换小程序</font> 后必须在锦帆制造后台更换下方参数。");
            $("#moreDataNotice").show();
        } else if (value == "gdt") {
            $("#moreDataTitle div").html("实现快手磁力建站一键拉起小程序微信小程序展示二维码");
            $("#moreDataNotice div").html("参数 <font class='text-warning'>有效期1年</font> 过期需复制新的更换；如<font class='text-warning'>更换小程序</font> 后必须在锦帆制造后台更换下方参数。");
            $("#moreDataNotice").show();
        } else if (value == "ks") {
            $("#moreDataTitle div").html("实现快手磁力建站一键拉起小程序微信小程序展示二维码");
            $("#moreDataNotice div").html("参数 <font class='text-warning'>有效期1年</font> 过期需复制新的更换；如<font class='text-warning'>更换小程序</font> 后必须在锦帆制造后台更换下方参数。");
            $("#moreDataNotice").show();
        } else if (value == "api") {
            $("#moreDataTitle div").html("实现快手磁力建站一键拉起小程序微信小程序展示二维码");
            $("#moreDataNotice div").html("参数 <font class='text-warning'>有效期1年</font> 过期需复制新的更换；如<font class='text-warning'>更换小程序</font> 后必须在锦帆制造后台更换下方参数。");
            $("#moreDataNotice").show();
        } else if (value == "js") {
            $("#moreDataTitle div").html("自己开发的落地页通过几行JS代码接入，即可实现自动拉起跳转小程序!");
            $("#moreDataNotice").hide();
            mviewToastr("info", "功能开发中,敬请期待!");
            return;
        } else {
            $("#moreDataTitle label").text("小程序码获取:");
            $("#moreDataNotice").hide();
            $("#moreDataTitle div").html("小程序码有效期1年,过期后需要重新获取!");
            getLinkMiniQrcode();
        }
    });

    $("#otherDateTime li").click(function() {
        $("#otherDateTime li").removeClass("active");
        $(this).addClass("active");
        var value = $(this).attr('data');
        renderOtherData(value);
    });

    $("#otherChartType li").click(function() {
        $("#otherChartType li").removeClass("active");
        $(this).addClass("active");
        var value = $(this).attr('data');
        $("#other_chart").val(value);
        renderOtherChart();
    });
    $("#recordExportDate li").click(function() {
        $("#recordExportDate li").removeClass("active");
        $(this).addClass("active");
        var value = $(this).attr('data');
        renderRecordExportTime(value);
    });
    showLinkModal();
});

function showLinkModal() {
    var links_id = $("#links_id").val();
    var linkModalShow = localStorage.getItem("linkModalShow_"+links_id) || 1;
    if (linkModalShow == 1) {
        copyPromotionUrl();
        localStorage.setItem("linkModalShow_"+links_id,2);
    }
}

function renderRecordExportTime(value) {
    if (value == "today") {
        var start = moment().format("YYYY-MM-DD");
        var end = moment().format("YYYY-MM-DD") + " 23:59:59";
    } else if (value == "yesterday") {
        var start = moment().subtract(1, "days").format("YYYY-MM-DD");
        var end = moment().subtract(1, "days").format("YYYY-MM-DD") + " 23:59:59";
    } else if (value == "thismonth") {
        var start = moment().startOf("month").format("YYYY-MM-DD");
        var end = moment().endOf("month").format("YYYY-MM-DD");
    } else if (value == "lastmonth") {
        var start = moment().subtract(1, "months").startOf("month").format("YYYY-MM-DD");
        var end = moment().subtract(1, "months").endOf("month").format("YYYY-MM-DD");
    }
    $("#record_export_start").val(start);
    $("#record_export_end").val(end);
    $("#recordExportDatePicker").val(start+" 至 "+end);
}

function renderOtherData(status) {
    if (status == "today") {
        $("#other_date_start").val(moment().format("YYYY-MM-DD"));
        $("#other_date_end").val(moment().format("YYYY-MM-DD") + " 23:59:59");
    } else if (status == "yesterday") {
        $("#other_date_start").val(moment().subtract(1, "days").format("YYYY-MM-DD"));
        $("#other_date_end").val(moment().subtract(1, "days").format("YYYY-MM-DD") + " 23:59:59");
    } else if (status == "thismonth") {
        $("#other_date_start").val(moment().startOf("month").format("YYYY-MM-DD"));
        $("#other_date_end").val(moment().endOf("month").format("YYYY-MM-DD"));
    } else if (status == "lastmonth") {
        $("#other_date_start").val(moment().subtract(1, "months").startOf("month").format("YYYY-MM-DD"));
        $("#other_date_end").val(moment().subtract(1, "months").endOf("month").format("YYYY-MM-DD"));
    }
    renderOtherChart();
}

function renderOtherChart() {
    linkDetialLoad.other = 1;
    var other_chart = $("#other_chart").val();
    otherChart();
}

function copyExtraData(type) {
    var mini_name = $("#mini_name").val();
    var mini_appid = $("#mini_appid").val();
    var miniapp_user = $("#miniapp_user").val();
    if (miniapp_user == 1) {
        mviewToastr("warning","必须上架独家小程序才能获取本参数!");
        return;
    }
    var mini_original_id = $("#mini_original_id").val();
    var mini_path = $("#mini_path").val();
    var mini_sign = $("#mini_sign").val();
    var links_id = $("#links_id").val();
    if (type == "mini_name") {
        copyWailianPath("天天外链-" + mini_name, "小程序名称");
    } else if (type == "mini_original_id") {
        copyWailianPath(mini_original_id, "小程序原始ID");
    } else if (type == "mini_path") {
        if (mini_path == "") {
            mviewToastr("当前小程序未配置小程序路径,请配置后再获取!");
        } else {
            copyWailianPath(mini_path, "小程序路径");
        }
    } else if (type == "scheme_bd") {
        copyWailianPath("https://sapi.wailian1.cn/api/urlscheme/" + links_id + "?osign=" + mini_sign + "&status=baidu", "Scheme接口");
    } else if (type == "scheme_uc") {
        copyWailianPath("https://sapi.wailian1.cn/api/urlscheme/" + links_id + "?sign=" + mini_sign + "&status=uc", "Scheme接口");
    } else if (type == "scheme_json") {
        copyWailianPath("https://sapi.wailian1.cn/api/urlscheme/" + links_id + "?sign=" + mini_sign + "&status=json", "Scheme接口API");
    } else if (type == "scheme_text") {
        copyWailianPath("https://sapi.wailian1.cn/api/urlscheme/" + links_id + "?sign=" + mini_sign + "&status=text", "Scheme接口API");
    }
}

function renderPlatformType() {
    var platfrom_type = parseInt($("#platfrom_type").val());
    if ($.inArray(platfrom_type, [8, 9, 11, 12]) != -1) {
        linkDetialLoad.qrcode = 2;
        qrcodeListReload();
        $("#linkDetialTable li[data=qrcode]").show().addClass("active");
    } else {
        linkDetialLoad.record = 2;
        setTimeout(function() {
            linkQrcodeAll(1);
        }, 100);
        $(".data-qrcode").hide();
        $(".data-record").show();
        $("#linkDetialTable li[data=qrcode]").hide();
        $("#linkDetialTable li[data=record]").show().addClass("active");
    }
}

function getLinkMiniQrcode() {
    var links_id = $("#links_id").val();
    if (miniQrcode != "") {
        $("#linkListMiniQrcode").attr("src", "/" + miniQrcode);
        return;
    }
    $.ajax({
        "url": "/admin/links_lists/link_list_mini_qrcode",
        "type": "GET",
        data: {
            "links_id": links_id,
        },
        success: function(res) {
            if (res.status == "success") {
                miniQrcode = res.data.qrcode_url;
                $("#linkListMiniQrcode").attr("src", "/" + res.data.qrcode_url);
            } else {
                mviewToastr("error", res.msg);
            }
        },
        error: function(err) {
            mviewToastr("error", "网络异常,请稍后重试！");
        }
    });
}

function qrcodeListRecordReload() {
    $tableRecord.bootstrapTable('refresh');
}

function qrcodeListRecordEmpty() {
    $("#code").val("");
    $("#mini_show_time").val(0);
    $("#mini_press_time").val(0);
    $("#mini_card_time").val(0);
    $("#province").val("");
}

function qrcodeListReload() {
    $table.bootstrapTable('refresh');
}

// 访问数据记录
function qrcodesListsData(status) {
    var chartDom = document.getElementById('overview-chart');
    var myChart = echarts.init(chartDom);
    if (linkDetialLoad.chart == 2 && status == 1) {
        myChart.resize();
        return;
    }
    myChart.clear();
    linkDetialLoad.chart = 2;
    var links_id = $("#links_id").val();
    var statistics_start = $("#statistics_start").val();
    var statistics_end = $("#statistics_end").val();
    var statistics_day = $("#statistics_day").val();
    var users_id = $("#users_id").val();
    var platfrom_type = parseInt($("#platfrom_type").val());
    var diff_day = moment(statistics_end).diff(moment(statistics_start), "days");
    var diff_today = moment().diff(moment(statistics_end), "days");
    $.ajax({
        url: "/api/version/1/links_static/daily",
        type: 'GET',
        dataType: 'json',
        data: {
            "links_id": links_id,
            "date_start": statistics_start,
            "date_end": statistics_end,
            "diff_day": diff_day,
            "users_id": users_id,
        },
        success: function(result) {
            if (result.status == "success") {
                var todaydate = new Date(new Date().setHours(0, 0, 0, 0));
                var yesterdaydate = new Date(new Date().setHours(0, 0, 0, 0) - 24 * 60 * 60 * 1000);
                var todaytime = todaydate.getTime() / 1000;
                var yesterdaytime = yesterdaydate.getTime() / 1000;

                var todaydata = {}
                var yesterdaydata = {}

                var datakey = [];
                var pageViews = [];
                var miniViews = [];
                var miniDirects = [];
                var miniPresss = [];
                var miniCards = [];

                $.each(result.data.statistics, function(idx, data) {
                    if (data.phase == todaytime) {
                        todaydata = data;
                    }
                    if (data.phase == yesterdaytime) {
                        yesterdaydata = data;
                    }
                    if (data.phase > 24) {
                        datakey.push(moment(data.phase, "YYYY-MM-DD").format("MM月DD日"));
                    } else {
                        datakey.push(data.phase + "点");
                    }
                    pageViews.push(data.page_view);
                    miniViews.push(data.mini_view);
                    miniDirects.push(data.mini_direct);
                    miniPresss.push(data.mini_press);
                    miniCards.push(data.mini_card);
                });
                if (diff_day > 0 && diff_today < 1) {
                    datakey.push(moment().format("MM月DD日"));
                    pageViews.push(linkTotalData.todayStatic.page_view);
                    miniViews.push(linkTotalData.todayStatic.mini_view);
                    miniDirects.push(linkTotalData.todayStatic.mini_direct);
                    miniPresss.push(linkTotalData.todayStatic.mini_press);
                    miniCards.push(linkTotalData.todayStatic.mini_card);
                }
                if ([1, 2, 3, 6, 13].includes(platfrom_type)) {
                    var dataKeyLists = ['链接访问量', '小程序访问量', '直接跳转小程序'];
                    var seriesLists = [{ name: '链接访问量', type: 'line', areaStyle: { color: '#556ee6', opacity: 0.1 }, smooth: true, data: pageViews }, { name: '小程序访问量', type: 'line', smooth: true, data: miniViews, }, { name: '直接跳转小程序', type: 'line', smooth: true, data: miniDirects, }]
                } else if ([8, 9, 11, 12].includes(platfrom_type)) {
                    var dataKeyLists = ['链接访问量', '直接跳转小程序', '二维码展示量', '长按识别二维码', '点击名片数量'];
                    var seriesLists = [{ name: '链接访问量', type: 'line', areaStyle: { color: '#556ee6', opacity: 0.1 }, smooth: true, data: pageViews }, { name: '直接跳转小程序', type: 'line', smooth: true, data: miniDirects, }, { name: '二维码展示量', type: 'line', smooth: true, data: miniViews, }, { name: '长按识别二维码', type: 'line', smooth: true, data: miniPresss }, { name: '点击名片数量', type: 'line', smooth: true, data: miniCards }]
                } else {
                    var dataKeyLists = ['链接访问量'];
                    var seriesLists = [{ name: '链接访问量', type: 'line', areaStyle: { color: '#556ee6', opacity: 0.1 }, smooth: true, data: pageViews }]
                }
                var option = {
                    color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            label: {
                                backgroundColor: '#6a7985',
                                precision: 0
                            }
                        }
                    },
                    legend: {
                        data: dataKeyLists
                    },
                    toolbox: {
                        feature: {
                            dataView: {
                                show: true,
                                title: '数据视图',
                                lang: ['数据视图', '关闭', '导出Excel'],
                                contentToOption: function(opts) {
                                    $("#tableExcel_Day").table2excel({
                                        exclude: ".noExl",
                                        filename: '访问数据',
                                        name: "Excel Document Name.xls",
                                        exclude_img: true,
                                        exclude_links: true,
                                        exclude_inputs: true
                                    });
                                },
                                optionToContent: function(opt) {
                                    var axisData = opt.xAxis[0].data; //坐标数据
                                    var series = opt.series; //折线图数据
                                    var tdHeads = '<td style="height: 30px;line-height:30px;">日期/时间</td>'; //表头第一列
                                    var tdBodys = ''; //表数据
                                    //组装表头
                                    for (var i = 0; i < dataKeyLists.length; i++) {
                                        tdHeads += '<td style="height: 30px;line-height:30px;">' + dataKeyLists[i] + '</td>';
                                    }
                                    var table = '<table id="tableExcel_Day" border="1" class="table-bordered table-striped" style="width:100%;text-align:center" ><tbody><tr>' + tdHeads + ' </tr>';
                                    //组装表数据
                                    for (var i = 0, l = axisData.length; i < l; i++) {
                                        for (var j = 0; j < series.length; j++) {
                                            var temp = series[j].data[i];
                                            if (temp != null && temp != undefined) {
                                                tdBodys += '<td>' + temp.toFixed(0) + '</td>';
                                            } else {
                                                tdBodys += '<td></td>';
                                            }
                                        }
                                        table += '<tr><td style="height: 30px;line-height:30px;">' + axisData[i] + '</td>' + tdBodys + '</tr>';
                                        tdBodys = '';
                                    }
                                    table += '</tbody></table>';
                                    return table;
                                }
                            },
                            saveAsImage: {
                                type: 'png',
                                title: '下载访问数据',
                                name: '访问数据'
                            }
                        }
                    },
                    grid: {
                        left: '0%',
                        right: '4%',
                        bottom: '0%',
                        containLabel: true
                    },
                    xAxis: [{
                        type: 'category',
                        boundaryGap: false,
                        data: datakey
                    }],
                    yAxis: [{
                        min: 0,
                        type: 'value',
                    }],
                    series: seriesLists
                };
                option && myChart.setOption(option);
            } else {
                mviewToastr("error", result.msg);
            }
        },
        error: function(err) {
            mviewToastr("error", "网络异常,请联系客服处理！");
        }
    });
}

// 获取总访问数据
function qrcodesTotalStatistic() {
    var links_id = $("#links_id").val();
    var users_id = $("#users_id").val();
    var left_pv = $("#left_pv").val();
    var platfrom_type = parseInt($("#platfrom_type").val());
    $.ajax({
        url: "/api/version/3/links_static/total",
        data: {
            "links_id": links_id,
            "users_id": users_id,
        },
        success: function(result) {
            if (result.status == "error") {
                mviewToastr("error", result.msg);
            } else {
                linkTotalData = result.data;
                $("#today_page_view").text(linkTotalData.todayStatic.page_view + "次");
                if ([1, 2, 3, 6, 13,14,15,16].includes(platfrom_type)) {
                    $("#today_mini_view").text(linkTotalData.todayStatic.mini_view + "人");
                    $("#today_mini_press").text("-");
                } else if (platfrom_type == 4 || platfrom_type == 5) {
                    $("#today_mini_view").text("-");
                    $("#today_mini_press").text("-");
                } else if (platfrom_type == 7 || platfrom_type == 10) {
                    $("#today_mini_view").text("-");
                    $("#today_mini_press").text("-");
                    $("#today_mini_card").text("-");
                    $("#today_mini_direct").text("-");
                } else {
                    $("#today_mini_view").text(linkTotalData.todayStatic.mini_view + "人");
                    $("#today_mini_press").text(linkTotalData.todayStatic.mini_press + "人");
                    $("#today_mini_card").text(linkTotalData.todayStatic.mini_card + "人");
                    $("#today_mini_direct").text(linkTotalData.todayStatic.mini_direct + "人");
                }
                var left_number = parseInt(left_pv) - parseInt(linkTotalData.todayStatic.page_view);
                if (left_number <= 0) {
                    $("#month_left_pv").text(0);
                } else {
                    $("#month_left_pv").text(left_number);
                }
                var limit_pv = parseInt($("#limit_pv").val());
                if (limit_pv > 1000) {
                    if (left_number <= 10000) {
                        $("#month_left_pv").after('<a href="/admin/prices/products_lists" class="badge badge-line" style="align-items: center;font-size: 13px;">升级会员</a>');
                    }
                } else {
                    $("#month_left_pv").after('<a href="/admin/prices/products_lists" class="badge badge-line" style="align-items: center;font-size: 13px;">开通会员</a>');
                }
            }
        },
        error: function(error) {
            mviewToastr("error", "请求失败,请联系客服处理！");
        }
    });
}

function statisticsDate(date) {
    $("#statisticChartDate li").removeClass("active");
    $("#statisticsDate_" + date).addClass("active");
    if (date == "today") {
        $("#statistics_start").val(moment().format("YYYY-MM-DD"));
        $("#statistics_end").val(moment().format("YYYY-MM-DD 23:59:59"));
        $("#statistics_day").val(0);
        $("#statisticsdate").val(moment().format("YYYY-MM-DD") + " 至 " + moment().format("YYYY-MM-DD"));
    } else if (date == "yesterday") {
        $("#statistics_start").val(moment().subtract(1, "days").format("YYYY-MM-DD"));
        $("#statistics_end").val(moment().subtract(1, "days").format("YYYY-MM-DD 23:59:59"));
        $("#statistics_day").val(0);
        $("#statisticsdate").val(moment().subtract(1, "days").format("YYYY-MM-DD") + " 至 " + moment().subtract(1, "days").format("YYYY-MM-DD"));
    } else {
        $("#statistics_start").val(moment().subtract(7, "days").format("YYYY-MM-DD"));
        $("#statistics_end").val(moment().subtract(1, "days").format("YYYY-MM-DD 23:59:59"));
        $("#statistics_day").val(6);
        $("#statisticsdate").val(moment().subtract(7, "days").format("YYYY-MM-DD") + " 至 " + moment().subtract(1, "days").format("YYYY-MM-DD"));
    }
}

function statisticRecordDate(date) {
    $("#recordDatePickerRow li").removeClass("active");
    $("#recordDatePickerRow li[data=" + date + "]").addClass("active");
    if (date == "today") {
        $("#record_data_start").val(moment().format("YYYY-MM-DD"));
        $("#record_data_end").val(moment().format("YYYY-MM-DD 23:59:59"));
        $("#recordDatePicker").val(moment().format("YYYY-MM-DD") + " 至 " + moment().format("YYYY-MM-DD"));
    } else if (date == "yesterday") {
        $("#record_data_start").val(moment().subtract(1, "days").format("YYYY-MM-DD"));
        $("#record_data_end").val(moment().subtract(1, "days").format("YYYY-MM-DD 23:59:59"));
        $("#recordDatePicker").val(moment().subtract(1, "days").format("YYYY-MM-DD") + " 至 " + moment().subtract(1, "days").format("YYYY-MM-DD"));
    } else if (date == "threeday") {
        $("#record_data_start").val(moment().subtract(3, "days").format("YYYY-MM-DD"));
        $("#record_data_end").val(moment().format("YYYY-MM-DD 23:59:59"));
        $("#recordDatePicker").val(moment().subtract(3, "days").format("YYYY-MM-DD") + " 至 " + moment().format("YYYY-MM-DD"));
    } else if (date == "sevenday") {
        $("#record_data_start").val(moment().subtract(7, "days").format("YYYY-MM-DD"));
        $("#record_data_end").val(moment().format("YYYY-MM-DD 23:59:59"));
        $("#recordDatePicker").val(moment().subtract(7, "days").format("YYYY-MM-DD") + " 至 " + moment().format("YYYY-MM-DD"));
    } else {
        $("#record_data_start").val(moment().subtract(30, "days").format("YYYY-MM-DD"));
        $("#record_data_end").val(moment().format("YYYY-MM-DD 23:59:59"));
        $("#recordDatePicker").val(moment().subtract(30, "days").format("YYYY-MM-DD") + " 至 " + moment().format("YYYY-MM-DD"));
    }
    qrcodeListRecordReload();
}

// 获取小程序其他数据统计
function otherChart() {
    if (linkDetialLoad.other == 2) {
        return;
    }
    linkDetialLoad.other = 2;
    $("#custom_loading").show();
    var links_id = $("#links_id").val();
    var users_id = $("#users_id").val();
    var other_date_start = $("#other_date_start").val();
    var other_date_end = $("#other_date_end").val();
    var other_chart = $("#other_chart").val();
    var diff_day = moment(other_date_end).diff(moment(other_date_start), "days");
    $.ajax({
        url: "/api/version/1/links_static/other",
        data: {
            "links_id": links_id,
            "users_id": users_id,
            "other_date_start": other_date_start,
            "other_date_end": other_date_end,
            "other_chart": other_chart,
            "diff_day": diff_day,
        },
        success: function(result) {
            if (result.status == "error") {
                mviewToastr("error", result.msg);
            } else {
                var text = "";
                var subtext = "";
                if (other_chart == "rate") {
                    otherRateChart(result.data.datas,diff_day);
                } else if (other_chart == "map") {
                    getLinksMap(result.data.datas);
                } else {
                    otherPieChart(result.data.datas);
                }
                $("#custom_loading").hide();
            }
        },
        error: function(error) {
            mviewToastr("error", "请求失败,请联系客服处理!");
        }
    });
}

function otherPieChart(datas) {
    var chartDom = document.getElementById('otherchart');
    var myChart = echarts.init(chartDom);
    myChart.clear();
    var dataLists = [];
    var colorLists = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
    $.each(datas, function(index, dataList) {
        dataLists.push({ "name": dataList.name, "value": dataList.value, "itemStyle": { "color": colorLists[index] } });
    });
    var other_chart = $("#other_chart").val();
    if (other_chart == "system") {
        var text = "操作系统";
        var subtext = "客户使用什么操作系统访问落地页";
    } else if (other_chart == "browser") {
        var text = "访问环境";
        var subtext = "链接通过什么浏览器/APP访问落地页";
    } else {
        var text = "设备类型";
        var subtext = "客户使用什么手机访问落地页";
    }
    var option = {
        title: {
            text: text,
            subtext: subtext,
            left: 'center'
        },
        tooltip: {
            trigger: 'item'
        },
        legend: {
            orient: 'vertical',
            left: 'left'
        },
        series: [{
            name: '访问数据',
            type: 'pie',
            radius: '50%',
            data: dataLists,
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }]
    };
    option && myChart.setOption(option);
    myChart.resize();
}

function otherRateChart(datas,diff_day) {
    var dataLists = [];
    var colorLists = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
    if (datas[0].value <= 0) {
        var subtext = "当前暂无转化数据";
    } else {
        if (diff_day > 1) {
            var subtext = "按月查询暂不统计当日数据";
        } else {
            var subtext = "访问落地页包括直接拉起小程序";
        }
    }
    $.each(datas,function(index, dataList) {
        dataLists.push({ "name": dataList.name, "value": dataList.value, "itemStyle": { "color": colorLists[index] } });
    });
    var option = {
        title: {
            text: '转化率',
            subtext: subtext,
            x: 'center'
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c}%'
        },
        toolbox: {
            feature: {
                dataView: { readOnly: false },
                restore: {},
                saveAsImage: {}
            }
        },
        legend: {
            data: ['访问链接', '展示二维码', '长按识别', '点击名片']
        },
        series: [{
            name: '转化率',
            type: 'funnel',
            left: '10%',
            top: 60,
            bottom: 60,
            width: '80%',
            min: 0,
            max: 100,
            minSize: '0%',
            maxSize: '100%',
            sort: 'descending',
            gap: 2,
            label: {
                show: true,
                position: 'inside'
            },
            labelLine: {
                length: 10,
                lineStyle: {
                    width: 1,
                    type: 'solid'
                }
            },
            itemStyle: {
                borderColor: '#fff',
                borderWidth: 1
            },
            emphasis: {
                label: {
                    fontSize: 20
                }
            },
            data: dataLists
        }]
    };
    var myChart = echarts.init(document.getElementById('otherchart'));
    myChart.clear();
    myChart.setOption(option);
    myChart.resize();
    $("#custom_loading").hide();
}

function getLinksMap(datas) {
    var provinceLists = [];
    $.each(datas, function(key, provinceList) {
        var name = provinceList.name.replace("省", "").replace("市", "");
        provinceLists.push({ "name": name, "value": provinceList.value });
    });
    var optionMap = {
        backgroundColor: '#FFFFFF',
        title: {
            text: '全国地图大数据',
            subtext: '海外地区目前无法在地图中显示',
            x: 'center'
        },
        tooltip: {
            trigger: 'item'
        },
        visualMap: {
            show: false,
        },
        series: [{
            name: '访问用户',
            type: 'map',
            mapType: 'china',
            roam: true,
            label: {
                normal: {
                    show: true
                },
                emphasis: {
                    show: false
                }
            },
            data: provinceLists
        }]
    };
    //初始化echarts实例
    var myChart = echarts.init(document.getElementById('otherchart'));
    myChart.clear();
    //使用制定的配置项和数据显示图表
    myChart.setOption(optionMap);
    myChart.resize();
    $("#custom_loading").hide();
}

function getTotalChart() {
    var chartDom = document.getElementById('totalChart');
    var myChart = echarts.init(chartDom);
    var dataLists = [];

    var colorLists = ['#5470c6','#5470c6','#fac858','#91cc75', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
    var colorIndex = 0;
    var platfrom_type = parseInt($("#platfrom_type").val());
    $.each(linkTotalData.totalStatic, function(key, linkTotal) {
        if ([1, 2, 3, 6, 13,14,15,16].includes(platfrom_type)) {
            if (key == "mini_card" || key == "mini_press") {
                return true;
            }
        } else if (platfrom_type == 4 || platfrom_type == 5) {
            if (key != "page_view") {
                return true;
            }
        } else if (platfrom_type == 7 || platfrom_type == 10) {
            if (key != "page_view") {
                return true;
            }
        }
        dataLists.push({"value":linkTotal+parseInt(linkTotalData.todayStatic[key]),"itemStyle":{"color":colorLists[colorIndex]}});
        colorIndex += 1;
    });
    if ([1, 2, 3, 6, 13,14,15,16].includes(platfrom_type)) {
        var datakey = ['访问落地页','直达小程序','小程序展示'];
    } else if (platfrom_type == 4 || platfrom_type == 5) {
        var datakey = ['访问落地页'];
    } else if (platfrom_type == 7 || platfrom_type == 10) {
        var datakey = ['访问落地页'];
    } else {
        var datakey = ['访问落地页', '直达小程序', '二维码展示', '长按识别量', '点击名片量'];
    }
    var option = {
        title: {
            text: '累计访问数据',
            subtext: "点击名片数量新版才有数据",
            x: 'left'
        },
        color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
        yAxis: {
            type: 'category',
            data: datakey
        },
        xAxis: {
            type: 'value'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#6a7985',
                    precision: 0
                }
            }
        },
        toolbox: {
            feature: {
                saveAsImage: {
                    type: 'png',
                    title: '下载累计访问数据',
                    name: '累计访问数据'
                }
            }
        },
        series: [{
            data: dataLists,
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
                color: 'rgba(180, 180, 180, 0.2)'
            }
        }]
    };
    myChart.setOption(option);
}

function copyWailianLinks(info, text) {
    $("#copylink").attr("data-clipboard-text", info);
    $("#copylink").attr("text", text);
    setTimeout(function() {
        $("#copylink").click();
    }, 100);
}

function copyWailianPath(info, text) {
    $("#copypath").attr("data-clipboard-text", info);
    $("#copypath").attr("text", text);
    setTimeout(function() {
        $("#copypath").click();
    }, 100);
}

function shortLinks(links_id, users_id, type) {
    $.ajax({
        "url": "/api/version/1/links/short_code",
        "type": "GET",
        data: {
            "links_id": links_id,
            "users_id": users_id,
        },
        success: function(res) {
            if (res.status == "success") {
                if (type == 1) {
                    copyWailianLinks(res.data.url, "短链接");
                } else {
                    $("#preview-qrcode").html("");
                    var qrcode = new QRCode(document.getElementById("preview-qrcode"), {
                        text: res.data.url,
                        width: 500,
                        height: 500,
                        colorDark: "#000000",
                        colorLight: "#ffffff",
                        correctLevel: QRCode.CorrectLevel.H
                    });
                    $("#qrcode-url-content font").text('短链接二维码预览');
                    $("#qrcode-url-des").text('请用手机浏览器扫码体验，如需下载，请鼠标右键保存到本地。');
                    setTimeout(() => {
                        $("#qrcode-mask").show();
                        $("#qrcode-url-content").css('display', 'flex');
                    }, 50)
                }
            } else {
                mviewToastr("error", res.msg);
            }
        },
        error: function(err) {
            mviewToastr("error", "请求失败,请稍后重试！");
        }
    });
}

function deleteLinks(links_id, users_id) {
    var currentUrl = window.location.href;
    $.ajax({
        "url": "/api/version/1/links/users_links_delete",
        "type": "GET",
        data: {
            "links_id": links_id,
            "users_id": users_id,
        },
        success: function(res) {
            if (res.status == "success") {
                mviewToastr("success", res.msg);
                if (currentUrl.indexOf("links_lists_detial") != -1) {
                    setTimeout(function() {
                        window.location.href = "/admin/links_lists/lists";
                    }, 2000);
                } else {
                    $("#link_" + links_id).remove();
                }
            } else {
                mviewToastr("error", res.msg);
            }
        },
        error: function(err) {
            mviewToastr("error", "网络异常,请稍后重试！");
        }
    });
}

function updateRemark(links_id) {
    $("#links_id").val(links_id);
    var remark = $("#remark_" + links_id).text();
    if (remark != "-") {
        $("#remark").val(remark);
    }
    $("#remarkModal").modal('toggle');
}

function ListsRemarkUpdateSubmit() {
    var links_id = $("#links_id").val();
    var remark = $("#remark").val();
    if (remark.length <= 2) {
        mviewToastr("error", "请输入2个字以上备注");
        return;
    }
    $.ajax({
        "url": "/admin/links_lists/links_lists_remark_update",
        "type": "GET",
        data: {
            "links_id": links_id,
            "remark": remark,
        },
        success: function(res) {
            if (res.status == "success") {
                $("#remark_" + links_id).text(remark);
                $("#remarkModal").modal('toggle');
                mviewToastr("success", res.msg);
            } else {
                mviewToastr("error", res.msg);
            }
        },
        error: function(err) {
            mviewToastr("error", "网络异常,请稍后重试！");
        }
    });
}

function showQrcodesImages(type, img_url, name) {
    $("#serviceModal").modal('toggle');
    $("#service_qrcode").attr("src", img_url);
    $("#service_text").text(name);
    $("#service_time").hide();
    $("#service_describe").text("如果需要下载二维码,请使用鼠标右键点击图片下载");
}

function qrcodesListsImagesAdd() {
    $("#qrcodeModal .modal-self-header h3").text("添加微信二维码");
    $("#qrcodeModal").modal('toggle');
    $("#qrcodes_id").val("");
    $("#qrcode_show").attr("src", "");
    $("#qrcode").val("");
    $("#qrcodes_name").val("");
    var expiration_time = moment().add(2, "years").format("YYYY-MM-DD");
    $("#expiration_time").val(expiration_time);
    $("#rate").val("50");
    $("#count_limit").val("100000");
    $("#qrcodesModalButtonAdd").show();
    $("#qrcodesModalButtonUpdate").hide();
}

function qudaoshow() {
    $("#qudaoModal .modal-self-header h3").text("添加渠道码");
    $("#qudaoModal").modal('toggle');
}

function deleteQrcodesImages(qrcodes_id, status) {
    var users_id = $("#users_id").val();
    var links_id = $("#links_id").val();
    $.ajax({
        "url": "/api/version/1/links/qrcodes_delete",
        "type": "POST",
        data: {
            "links_id": links_id,
            "qrcodes_id": qrcodes_id,
            "users_id": users_id,
            "status": status,
        },
        success: function(res) {
            if (res.status == "success") {
                $("#qrcodes_lists_row_" + qrcodes_id).remove();
                qrcodeListReload();
                mviewToastr("success", res.msg);
            } else {
                mviewToastr("error", res.msg);
            }
        },
        error: function(err) {
            mviewToastr("error", "网络异常,请稍后重试！");
        }
    });
}

function qrcodesListsImagesAddSubmit() {
    var qrcode = $("#qrcode").val();
    if (qrcode == "") {
        mviewToastr("error", "请上传二维码!");
        return;
    }
    var qrcodes_name = $("#qrcodes_name").val();
    var expiration_time = $("#expiration_time").val();
    if (expiration_time == "") {
        mviewToastr("error", "请选择二维码有效期!");
        return;
    }
    var rate = $("#rate").val();
    if (rate == "") {
        mviewToastr("error", "请输入二维码权重!");
        return;
    }
    var count_limit = $("#count_limit").val();
    if (count_limit == "") {
        mviewToastr("error", "请输入二维码访问上限!");
        return;
    }
    var users_id = $("#users_id").val();
    var links_id = $("#links_id").val();
    $.ajax({
        "url": "/api/version/1/links/qrcodes_add",
        "type": "POST",
        data: {
            "links_id": links_id,
            "users_id": users_id,
            "qrcode": qrcode,
            "qrcodes_name": qrcodes_name,
            "expiration_time": expiration_time,
            "rate": rate,
            "count_limit": count_limit,
        },
        success: function(res) {
            if (res.status == "success") {
                qrcodeListReload();
                $("#qrcodeModal").modal('toggle');
                mviewToastr("success", res.msg);
            } else {
                mviewToastr("error", res.msg);
            }
        },
        error: function(err) {
            mviewToastr("error", "网络异常,请稍后重试！");
        }
    });
}

function qrcodesListsImagesUpdateSubmit() {
    var qrcodes_id = $("#qrcodes_id").val();
    var qrcode = $("#qrcode").val();
    if (qrcode == "") {
        mviewToastr("error", "请上传二维码!");
        return;
    }
    var qrcodes_name = $("#qrcodes_name").val();
    var expiration_time = $("#expiration_time").val();
    if (expiration_time == "") {
        mviewToastr("error", "请选择二维码有效期!");
        return;
    }
    var rate = $("#rate").val();
    if (rate == "") {
        mviewToastr("error", "请输入二维码权重!");
        return;
    }
    var count_limit = $("#count_limit").val();
    if (count_limit == "") {
        mviewToastr("error", "请输入二维码访问上限!");
        return;
    }
    var users_id = $("#users_id").val();
    var links_id = $("#links_id").val();
    $.ajax({
        "url": "/api/version/1/links/qrcodes_update",
        "type": "POST",
        data: {
            "links_id": links_id,
            "qrcodes_id": qrcodes_id,
            "users_id": users_id,
            "qrcode": qrcode,
            "qrcodes_name": qrcodes_name,
            "expiration_time": expiration_time,
            "rate": rate,
            "count_limit": count_limit,
        },
        success: function(res) {
            if (res.status == "success") {
                qrcodeListReload();
                $("#qrcodeModal").modal('toggle');
                mviewToastr("success", res.msg);
            } else {
                mviewToastr("error", res.msg);
            }
        },
        error: function(err) {
            mviewToastr("error", "网络异常,请稍后重试！");
        }
    });
}

function staticMore() {
    var display = $("#static_more").css('display');
    if (display == "none") {
        $("#staticMore").css("transform","rotate(180deg)");
    } else {
        $("#staticMore").css("transform","rotate(0deg)");
    }
    $("#static_more").slideToggle();
}

function copyTestUrl() {
    $("#qudaoModal .modal-self-header h3").text("获取测试链接");
    $("#platfrom_typeul_1").hide();
    $("#platfrom_typeul_2").hide();
    $("#platfrom_typeul_3").hide();
    $("#platfrom_typeul_4").hide();
    $("#platfrom_typeul_5").show();
    $("#platfrom_typeul_6").hide();
    $("#platfrom_typeul_7").hide();
    $("#platfrom_typeul_8").show();
    $("#platfrom").val(8);
    $("#country_row").hide();
    $("#qudaoModal").modal('toggle');
    $("#channel").hide();
    $("#channel_code").val("");
    $(".modal-self-describe p").text("温馨提示：");
    $("#country_notice").show();
    $("#country_notice").html("测试链接仅用于测试，正式推广/投放时请开通会员后获取推广链接。");
    $("#platfrom_notice").hide();
    $("#platfrom_help_dy").hide();
    $("#platfrom_help_dx").hide();
    $("#platfrom_help_bd").hide();
    $("#platfrom_help_other").hide();
    $.fn.modal.Constructor.prototype._enforceFocus = function() {};
}

function copyPromotionUrl() {
    $("#platfrom_typeul_8").hide();
    $("#qudaoModal .modal-self-header h3").text("获取推广链接");
    $("#qudaoModal").modal('toggle');
    $("#channel").hide();
    $("#channel_code").val("");
    $.fn.modal.Constructor.prototype._enforceFocus = function() {};
}

function linkListsCopy() {
    var channel = $("#channel_code").val();
    var country = $("#country").val();
    var platfrom = $("#platfrom").val();
    var links_day = $("#links_day").val();
    var links_id = $("#links_id").val();
    var users_id = $("#users_id").val();
    var linksurl = "";
    if (country == 1) {
        if (platfrom == 1) {
            linksurl = "https://s.pdb2.com/pages/" + links_day + "/" + links_id + ".html";
        } else if (platfrom == 2) {
            linksurl = "http://dy.pdb2.com/pages/" + links_day + "/" + links_id + ".html";
        } else if (platfrom == 3) {
            linksurl = "https://s.pdb2.com/l/" + links_id;
        } else if (platfrom == 4) {
            linksurl = "http://www.aixin7.cn/pages/" + links_day + "/" + links_id + ".html";
        } else if (platfrom == 5) {
            shortLinks(links_id, users_id, 1);
            return;
        } else if (platfrom == 6) {
            linksurl = "http://bd.pdb2.com/pages/" + links_day + "/" + links_id + ".html";
        } else if (platfrom == 7) {
            linksurl = "http://ga.shiganyi.cn/pages/" + links_day + "/" + links_id + ".html";
        } else if (platfrom == 9) {
            linksurl = $("#douyinlink").val() + "/l/" + links_id;
        } else {
            // 测试链接
            linksurl = "http://test.mpay8.cn/pages/" + links_day + "/" + links_id + ".html";
        }
    } else if (country == 2) {
        if (platfrom == 1) {
            linksurl = "http://abroad.pdb2.com/pages/" + links_day + "/" + links_id + ".html";
        } else if (platfrom == 5) {
            shortLinks(links_id, users_id, 1);
            return;
        } else if (platfrom == 9) {
            linksurl = $("#douyinlink").val() + "/l/" + links_id;
        }
    } else if (country == 3) {
        if (platfrom == 1) {
            linksurl = "http://global.pdb2.com/pages/" + links_day + "/" + links_id + ".html";
        } else if (platfrom == 5) {
            shortLinks(links_id, users_id, 1);
            return;
        } else if (platfrom == 9) {
            linksurl = $("#douyinlink").val() + "/l/" + links_id;
        }
    } else {
        if (platfrom == "") {
            mviewToastr("error", "您暂未绑定自有域名，请绑定后获取！");
            return;
        }
        linksurl = "http://"+platfrom + "/pages/" + links_day + "/" + links_id + ".html";
    }
    if (linksurl == "") {
        mviewToastr("error", "未获取到推广链接，请联系客服处理！");
        return;
    }
    if (channel != "") {
        linksurl = linksurl + "?channel=" + channel;
    }
    var platfroms = ["", "通用链接", "抖音推广", "微信广告", "微博专用", "短链接", "百度推广", "群分享", "测试链接", "抖音私信"];
    copyWailianLinks(linksurl, platfroms[platfrom]);
}

function linkListsQrcode() {
    var channel = $("#channel_code").val();
    var country = $("#country").val();
    var platfrom = $("#platfrom").val();
    var links_day = $("#links_day").val();
    var links_id = $("#links_id").val();
    var users_id = $("#users_id").val();
    var linksurl = "";
    if (country == 1) {
        if (platfrom == 1) {
            linksurl = "https://s.pdb2.com/pages/" + links_day + "/" + links_id + ".html";
        } else if (platfrom == 2) {
            linksurl = "http://dy.pdb2.com/pages/" + links_day + "/" + links_id + ".html";
        } else if (platfrom == 3) {
            linksurl = "https://s.pdb2.com/l/" + links_id;
        } else if (platfrom == 4) {
            linksurl = "http://www.aixin7.cn/pages/" + links_day + "/" + links_id + ".html";
        } else if (platfrom == 5) {
            shortLinks(links_id, users_id, 2);
            return;
        } else if (platfrom == 6) {
            linksurl = "http://bd.pdb2.com/pages/" + links_day + "/" + links_id + ".html";
        } else if (platfrom == 7) {
            linksurl = "http://ga.shiganyi.cn/pages/" + links_day + "/" + links_id + ".html";
        } else if (platfrom == 9) {
            linksurl = $("#douyinlink").val() + "/l/" + links_id;
        } else {
            // 测试链接
            linksurl = "http://test.mpay8.cn/pages/" + links_day + "/" + links_id + ".html";
        }
    } else if (country == 2) {
        if (platfrom == 1) {
            linksurl = "http://abroad.pdb2.com/pages/" + links_day + "/" + links_id + ".html";
        } else if (platfrom == 5) {
            shortLinks(links_id, users_id, 2);
            return;
        } else if (platfrom == 9) {
            linksurl = $("#douyinlink").val() + "/l/" + links_id;
        }
    } else if (country == 3) {
        if (platfrom == 1) {
            linksurl = "http://global.pdb2.com/pages/" + links_day + "/" + links_id + ".html";
        } else if (platfrom == 5) {
            shortLinks(links_id, users_id, 2);
            return;
        } else if (platfrom == 9) {
            linksurl = $("#douyinlink").val() + "/l/" + links_id;
        }
    } else {
        if (platfrom == "") {
            mviewToastr("error", "您暂未绑定自有域名，请绑定后获取！");
            return;
        }
        linksurl = "http://"+platfrom + "/pages/" + links_day + "/" + links_id + ".html";
    }
    if (linksurl == "") {
        mviewToastr("error", "未获取到推广链接，请联系客服处理！");
        return;
    }
    if (channel != "") {
        linksurl = linksurl + "?channel=" + channel;
    }
    $("#preview-qrcode").html("");
    var qrcode = new QRCode(document.getElementById("preview-qrcode"), {
        text: linksurl,
        width: 500,
        height: 500,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });
    var platfroms = ["", "通用链接", "抖音推广", "微信广告", "微博专用", "短链接", "百度推广", "群分享", "测试链接", "抖音私信"];
    if (country <= 3) {
        $("#qrcode-url-content font").text(platfroms[platfrom] + '二维码预览');
    } else {
        $("#qrcode-url-content font").text('自有域名二维码预览');
    }
    if (['2', '9'].includes(platfrom)) {
        var des = '请用抖音扫码体验';
    } else if (['3', '7'].includes(platfrom)) {
        var des = '请用微信扫码体验';
    } else if (platfrom == '4') {
        var des = '请用微博扫码体验';
    } else if (platfrom == '6') {
        var des = '请用百度APP扫码体验';
    } else {
        var des = '请用手机浏览器扫码体验';
    }
    $("#qrcode-url-des").text(des + '，如需下载，请鼠标右键保存到本地。');
    setTimeout(() => {
        $("#qrcode-mask").show();
        $("#qrcode-url-content").css('display', 'flex');
    }, 50)
}

function confirmMviewNotification() {
    var mviewNotificationData = $("#mviewNotificationData").val();
    var notificationData = JSON.parse(mviewNotificationData);

    if (notificationData.type == "link_delete") {
        deleteLinks(notificationData.links_id, notificationData.users_id);
    } else if (notificationData.type == "qecodedelete") {
        deleteQrcodesImages(notificationData.qrcodes_id, 3);
    } else if (notificationData.type == "qecodeoff") {
        deleteQrcodesImages(notificationData.qrcodes_id, 2);
    } else if (notificationData.type == "qecodeon") {
        deleteQrcodesImages(notificationData.qrcodes_id, 1);
    }
    colseMviewNotification();
    console.log(notificationData);
}

function hideqrcodeurl() {
    $("#qrcode-url-content").css('display', 'none');
    $("#qrcode-mask").hide();
}

function testurlqrcode() {
    linksurl = "https://s.pdb2.com/pages/" + $("#links_day").val() + "/" + $("#links_id").val() + ".html?debug_time=" + $("#debug_time").val() + "&debug_sign=" + $("#debug_sign").val();
    $("#limit_qrcode").html("");
    var qrcode = new QRCode(document.getElementById("limit_qrcode"), {
        text: linksurl,
        width: 200,
        height: 200,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });
    $("#limitQrcodePreviewModal").modal('toggle');
}

function loadingTemplate(message) {
    return '<div style="font-size:14px;display: flex;align-items: center;flex-direction: row;"><i class="bx bx-loader-alt bx-spin me-2"></i>数据加载中,请稍等...</div>'
}

function getQrcodeImageStatus(qrcodeListImageList) {
    if (qrcodeListImageList.status != 1) return '<font class="text-warning">未上线</font>';
    var currentTime = moment().unix();
    if (currentTime >= qrcodeListImageList.expiration_time) {
        return '<font class="text-warning">已过期</font>';
    } else {
        var work_time = $("#work_time").val();
        var limit_number = $("#limit_number").val();
        var switch_type = $("#switch").val();
        var limit_type = $("#limit_type").val();
        if (work_time == 1) {
            var currentHour = parseInt(moment().format("HH"));
            var workTimes = JSON.parse(qrcodeListImageList.work_time);
            if ($.inArray(currentHour, workTimes) < 0) {
                return '<font class="text-warning">定时下线</font>';
            }
        }
        if (limit_type == 2) {
            if (limit_number == qrcodeListImageList.scan_today) return '<font class="text-warning">今日访问上限</font>';
        } else {
            if (qrcodeListImageList.scan_total > qrcodeListImageList.count_limit) return '<font class="text-warning">累计访问上限</font>';
        }
    }
    return '<font class="text-success">上线中</font>';
}

function qrcodesListsImageLists(params) {
    if (linkDetialLoad.qrcode == 1) {
        return;
    }
    linkDetialLoad.qrcode = 3;
    params.data.qrcode_name = $("#qrcode_name").val();
    params.data.users_id = $("#users_id").val();
    params.data.links_id = $("#links_id").val();
    params.data.page = Number(params.data.offset / params.data.limit) + 1;
    $.ajax({
        url: '/api/version/3/links/qrcode_list',
        type: 'GET',
        data: params.data,
        success: function(result) {
            if (result.status == "success") {
                if (result.data.total == 0 && $("#qrcode_name").val() == '') {
                    qrcodesListsImagesAdd();
                }
                var qrcodeListImageLists = [];
                $.each(result.data.data, function(key, qrcodeListImageList) {
                    allQrcodesListsImage.push(qrcodeListImageList);
                    var expirationTime = moment(qrcodeListImageList.expiration_time * 1000).format("YYYY/MM/DD");
                    var show_status = getQrcodeImageStatus(qrcodeListImageList);
                    if (qrcodeListImageList.status == 1) {
                        var xiajiaNotice = '<a href="javascript:;" class="table-handdle-link text-warning" onclick=\'mviewNotification("warning","子二维码下架提醒","子二维码下架后无法展示,请确认是否下架？","确认下架","取消",{"type":"qecodeoff","qrcodes_id":"' + qrcodeListImageList.qrcodes_id + '","key":"' + key + '"});\'>下架</a>';
                    } else if (qrcodeListImageList.status == 2) {
                        var xiajiaNotice = '<a href="javascript:;" class="table-handdle-link text-success" onclick=\'mviewNotification("success","子二维码上架提醒","子二维码上架后可以继续展示,请确认是否上架？","确认上架","取消",{"type":"qecodeon","qrcodes_id":"' + qrcodeListImageList.qrcodes_id + '","key":"' + key + '"});\'>上架</a>';
                    } else {
                        var xiajiaNotice = '<a href="javascript:;" class="table-handdle-link text-warning">已删除</a>';
                    }
                    var recordsList = { "name": qrcodeListImageList.name, "rate": qrcodeListImageList.rate, "expiration_time": expirationTime, "count_limit": qrcodeListImageList.count_limit, "scan_today": qrcodeListImageList.scan_today, "scan_total": qrcodeListImageList.scan_total, "show_status": show_status };
                    recordsList.qrcode = '<a href="javascript:;" class="text-dark" onclick="showQrcodesImages(\'qrcode\',\'' + qrcodeListImageList.img_url + '\',\'' + qrcodeListImageList.name + '\');">查看</a>';
                    recordsList.method = '<div class="table-handdle"><a href="javascript:;" class="table-handdle-link" onclick="qrcodesListsImagesUpdate(\'' + qrcodeListImageList.qrcodes_id + '\');">更新</a>' + xiajiaNotice + '<a href="javascript:;" class="table-handdle-last text-danger" onclick=\'mviewNotification("error","子二维码删除提醒","子二维码删除后无法恢复,请确认是否删除？","确认删除","取消",{"type":"qecodedelete","qrcodes_id":"' + qrcodeListImageList.qrcodes_id + '","key":"' + key + '"});\'>删除</a></div>';
                    qrcodeListImageLists.push(recordsList);
                });
                var dataResult = {};
                dataResult.rows = qrcodeListImageLists;
                dataResult.total = result.data.total;
                params.success(dataResult);
            } else {
                mviewToastr("error", result.msg);
            }
        },
        error: function(err) {
            mviewToastr("error", "网络异常,请联系客服处理！");
        }
    });
}

function qrcodesListsImagesUpdate(qrcodes_id) {
    var index = allQrcodesListsImage.findIndex(qrcodesListsImage => {
        return qrcodesListsImage.qrcodes_id == qrcodes_id;
    });
    var qrcodeListImage = allQrcodesListsImage[index];
    $("#qrcodeModal .modal-self-header h3").text("更新微信二维码");
    $("#qrcodeModal").modal('toggle');
    $("#qrcodes_id").val(qrcodes_id);
    $("#qrcode_show").attr("src", qrcodeListImage.img_url);
    $("#qrcode").val(qrcodeListImage.img_url);
    $("#qrcodes_name").val(qrcodeListImage.name);
    var expiration_time = moment(qrcodeListImage.expiration_time * 1000).format("YYYY-MM-DD");
    $("#expiration_time").val(expiration_time);
    $("#rate").val(qrcodeListImage.rate);
    $("#count_limit").val(qrcodeListImage.count_limit);
    $("#qrcodesModalButtonAdd").hide();
    $("#qrcodesModalButtonUpdate").show();
}

function linkQrcodeAll(status) {
    var links_id = $("#links_id").val();
    var users_id = $("#users_id").val();
    $.ajax({
        url: "/admin/links_lists/links_qrcode_all",
        type: 'GET',
        data: {
            "links_id": links_id,
            "users_id": users_id,
        },
        dataType: 'json',
        success: function(result) {
            if (result.status == "success") {
                linkQrcodes = result.data.linkQrcodes;
                if (status == 1) {
                    statisticRecordDate("today");
                }
            } else {
                messageToastr("error", result.msg);
            }
        }
    });
}

function recodeLists(params) {
    if (linkDetialLoad.record == 1) {
        return;
    }
    linkDetialLoad.record = 3;
    params.data.start_time = $("#record_data_start").val();
    params.data.end_time = $("#record_data_end").val();
    params.data.links_id = $("#links_id").val();
    params.data.mini_show_time = $("#mini_show_time").val();
    params.data.mini_press_time = $("#mini_press_time").val();
    params.data.mini_card_time = $("#mini_card_time").val();
    params.data.province = $("#province").val();
    params.data.code = $("#code").val();
    params.data.total = nextRecordData.total;
    params.data.total_end = nextRecordData.total_end;
    params.data.total_start = nextRecordData.total_start;
    var platfrom_type = parseInt($("#platfrom_type").val());
    params.data.page = (params.data.offset == 0) ? 1 : parseInt(params.data.offset/params.data.limit)+1;
    if ($.inArray(platfrom_type, [2,4,5,6,10,7]) != -1) {
        $("#mini_show_time").parent().remove();
        $("#mini_press_time").parent().remove();
        $("#mini_card_time").parent().remove();
        $tableRecord.bootstrapTable('hideColumn', ["web_time", "name", "mini_press_time", "mini_card_time", "mini_show_time"]);
    }

    $.ajax({
        url: "/admin/links_lists/links_record",
        type: 'GET',
        data: params.data,
        dataType: 'json',
        success: function(result) {
            if (result.status == "success") {
                var qrRecordLists = [];
                linkRecordLists = result.data.data;
                $.each(result.data.data, function(key, item) {
                    if ($.inArray(platfrom_type, [2,4,5,6,10,7]) == -1) {
                        var web_time = item.web_time <= 1 ? '<font class="text-warning">直接跳转</font>' : '链接跳转';
                        var mini_show_time = item.mini_show_time <= 1 ? '未展示' : '<font class="text-success">已展示</font>';
                        var mini_press_time = item.mini_press_time <= 1 ? '未长按' : '<font class="text-success">已长按</font>';
                        var mini_card_time = item.mini_card_time <= 1 ? '未点击' : '<font class="text-success">已点击</font>';
                        var name = "-";
                        if (item.mini_show_time > 1) {
                            name = getRecordType(item.qrcodes_id, "qrcode");
                        }
                    }
                    var code = (item.code == "") ? '-' : item.code;
                    var step_add = item.step_add > 1680000 ? '<font class="text-success">已添加</font>' : '-';
                    var browser = getRecordType(item.browser, "browser");
                    var system = getRecordType(item.system, "system");
                    var device = getRecordType(item.device, "device");
                    var model = getRecordType(item.model, "model");
                    var created_at = moment(item.created_at).format("YYYY-MM-DD HH:mm:ss")
                    var method = '<font class="text-primary" data-bs-toggle="offcanvas" href="#showRecordDetails" role="button" aria-controls="showRecordDetails" onclick="showRecordDetails(\'' + item.record_id + '\')">详情</font>';
                    if ($.inArray(platfrom_type, [2,4,5,6,10,7]) == -1) {
                        var qrRecordList = { "province": item.province, "city": item.city, "ip": item.ip, "system": system, "code": code, "device": device, "model": item.model, "name": name, "web_time": web_time, "mini_show_time": mini_show_time, "mini_press_time": mini_press_time, "mini_card_time": mini_card_time, "browser": browser, "created_at": created_at, "method": method };
                    } else {
                        var qrRecordList = { "province": item.province, "city": item.city, "ip": item.ip, "system": system, "code": code, "device": device, "model": item.model, "browser": browser, "created_at": created_at, "method": method };
                    }
                    qrRecordLists.push(qrRecordList);
                });
                if (result.data.total_end !== undefined) {
                    nextRecordData = { "total": result.data.total, "total_end": result.data.total_end, "total_start": result.data.total_start };
                }
                var dataResult = {};
                dataResult.rows = qrRecordLists;
                dataResult.total = result.data.total;
                params.success(dataResult);
            } else {
                messageToastr("error", result.msg);
            }
        }
    });
}

function showRecordDetails(record_id) {
    $("#qrcodeRecordTime").html("");
    var index = linkRecordLists.findIndex(linkRecordList => {
        return linkRecordList.record_id == record_id;
    });
    var linkRecord = linkRecordLists[index];
    var platfrom_type = parseInt($("#platfrom_type").val());
    if ($.inArray(platfrom_type, [2, 4, 5, 6, 10]) != -1) {
        $("#qrcodeshow").hide();
        if (linkRecord.web_time > 1) {
            $("#qrcodeRecordTime").append("<tr><td>访问落地页</td><td>" + moment(linkRecord.web_time * 1000).format("YYYY-MM-DD HH:mm:ss") + "</td></tr>");
        } else {
            $("#qrcodeRecordTime").append("<tr><td>访问落地页</td><td>未访问</td></tr>");
        }
        $("#qrcodeRecordTime").append("<tr><td>小程序打开时间</td><td>-</td></tr>");
        $("#qrcodeRecordTime").append("<tr><td>小程序关闭时间</td><td>-</td></tr>");
        $(".m-info-item .text").remove();
        $(".m-info-item label").append('<div class="text">推广小程序无法统计小程序内操作,具体请前往小程序后台查看!</div>');
    } else {
        var qrindex = linkQrcodes.findIndex(linkQrcode => {
            return linkQrcode.qrcodes_id == linkRecord.qrcodes_id;
        });
        if (qrindex >= 0) {
            $("#recodeQrcodeImage").attr("src", linkQrcodes[qrindex].img_url);
            $("#qrcodeshow").show();
        } else {
            $("#qrcodeshow").hide();
        }
        if (linkRecord.web_time > 1) {
            $("#qrcodeRecordTime").append("<tr><td>访问落地页</td><td>" + moment(linkRecord.web_time * 1000).format("YYYY-MM-DD HH:mm:ss") + "</td></tr>");
        } else {
            $("#qrcodeRecordTime").append("<tr><td>访问落地页</td><td>未访问</td></tr>");
        }
        if (linkRecord.mini_open_time > 1) {
            $("#qrcodeRecordTime").append("<tr><td>小程序打开时间</td><td>" + moment(linkRecord.mini_open_time * 1000).format("YYYY-MM-DD HH:mm:ss") + "</td></tr>");
        } else {
            $("#qrcodeRecordTime").append("<tr><td>小程序打开时间</td><td>未打开</td></tr>");
        }
        if (linkRecord.mini_show_time > 1) {
            $("#qrcodeRecordTime").append("<tr><td>小程序展示时间</td><td>" + moment(linkRecord.mini_show_time * 1000).format("YYYY-MM-DD HH:mm:ss") + "</td></tr>");
        } else {
            $("#qrcodeRecordTime").append("<tr><td>小程序展示时间</td><td>未展示</td></tr>");
        }
        if (linkRecord.mini_press_time > 1) {
            $("#qrcodeRecordTime").append("<tr><td>长按识别时间</td><td>" + moment(linkRecord.mini_press_time * 1000).format("YYYY-MM-DD HH:mm:ss") + "</td></tr>");
        } else {
            $("#qrcodeRecordTime").append("<tr><td>长按识别时间</td><td>未长按</td></tr>");
        }
        if (linkRecord.mini_card_time > 1) {
            $("#qrcodeRecordTime").append("<tr><td>点击名片时间</td><td>" + moment(linkRecord.mini_card_time * 1000).format("YYYY-MM-DD HH:mm:ss") + "</td></tr>");
        } else {
            $("#qrcodeRecordTime").append("<tr><td>点击名片时间</td><td>未点击</td></tr>");
        }
        if (linkRecord.mini_hide_time > 1) {
            $("#qrcodeRecordTime").append("<tr><td>页面关闭时间</td><td>" + moment(linkRecord.mini_hide_time * 1000).format("YYYY-MM-DD HH:mm:ss") + "</td></tr>");
        } else {
            $("#qrcodeRecordTime").append("<tr><td>页面关闭时间</td><td>未关闭</td></tr>");
        }
    }
}

function recordExportExcel(){
    renderRecordExportTime("today");
    $('#linksRecordExport').modal('toggle');
}

function recordExportExcelSubmit(){
    var record_export_start = moment($("#record_export_start").val());
    var record_export_end = moment($("#record_export_end").val());
    var todayDiffMonth = moment().diff(record_export_start, "month");
    if (todayDiffMonth >= 3) {
        mviewToastr("warning","天天外链无法查看3个月以上数据!");
        return;
    }
    var difmonth = record_export_end.diff(record_export_start, "month");
    if (difmonth >= 3) {
        mviewToastr("warning","导出开始时间不得少于1个月!");
        return;
    }
    var difday = record_export_end.diff(record_export_start, "day");
    if (difday >= 31) {
        mviewToastr("warning","时间跨度不能超过31天!");
        return;
    }
    if (record_export_start.format("MM") != record_export_end.format("MM")) {
        mviewToastr("warning","导出时间不支持跨月，请选择同一月份!");
        return;
    }
    var export_email = $("#export_email").val();
    if (export_email == "") {
        mviewToastr("warning","请设置数据接收邮箱!");
        return;
    }
    var links_id = $("#links_id").val();
    var time_start = $("#record_export_start").val();
    var time_end = $("#record_export_end").val();
    $.ajax({
        "url": "/admin/links_lists/link_list_export",
        "type": "GET",
        data: {
            "links_id": links_id,
            "time_start": time_start,
            "time_end": time_end,
        },
        success: function(res) {
            if (res.status == "success") {
                mviewToastr("success", res.msg);
                $('#linksRecordExport').modal('toggle');
            } else {
                mviewToastr("error", res.msg);
            }
        },
        error: function(err) {
            mviewToastr("error", "网络异常,请稍后重试！");
        }
    });
}

function userDomainList() {
    $.ajax({
        "url": "/admin/users/domain_list",
        "type": "GET",
        data: {
            "type": "json",
        },
        success: function(result) {
            if (result.status == "success") {
                if (result.data.usersDomains.length <= 0) {
                    $("#platfrom_notice").html("<b>温馨提示：</b>您当前暂未绑定域名，点击<a href='/admin/users/domain_list' target='_blank'>绑定自有域名<i class='bx bx-chevron-right'></i></a>！");
                    $("#platfrom").val("");
                } else {
                    $.each(result.data.usersDomains, function(idx, usersDomain) {
                        var classStyle = (idx == 0) ? "platfrom_typeul_self active" : "platfrom_typeul_self";
                        $("#platfrom_typeul").append('<li id="platfrom_typeul_self" class="'+classStyle+'">'+usersDomain.domain+'</li>');
                    });
                    $("#platfrom").val(result.data.usersDomains[0].domain);
                }
            } else {
                mviewToastr("error", result.msg);
            }
        },
        error: function(err) {
            mviewToastr("error", "网络异常,请稍后重试！");
        }
    });
}

function jsUploadCallBack(id, imageurl, imageName, updata) {
    console.log(id);
    console.log(imageurl);
    console.log(imageName);
    console.log(updata);
}

function cardEditChange(object) {
    var id = object.id;
    var value = object.value;
    if (id == "dycard_title") {
        $(".card-preview h3").text(value);
    } else if (id == "dycard_describe") {
        $(".card-preview h5").text(value);
    } else {
        $(".card-preview img").attr("src", value);
    }
}

function getRecordType(key, type) {
    if (type == "system") {
        var arr = ["-", "安卓", "苹果", "Win", "Mac"]
        try {
            return arr[key];
        } catch (e) {
            return '-';
        }
    } else if (type == "device") {
        var arr = ["其他", "华为", "Vivo", "小米", "OPPO", "三星", "苹果"];
        try {
            return arr[key];
        } catch (e) {
            return '-';
        }
    } else if (type == "qrcode") {
        var index = linkQrcodes.findIndex(linkQrcode => {
            return linkQrcode.qrcodes_id == key;
        });
        if (index >= 0) {
            return linkQrcodes[index].name;
        } else {
            return '-';
        }
    } else {
        var browsers = ["", "微信浏览器", "电脑QQ浏览器", "Vivo浏览器", "Oppo浏览器", "华为浏览器", "小米浏览器", "QQ浏览器", "支付宝浏览器", "百度APP", "微博浏览器", "爱奇艺浏览器", "小米浏览器", "喜马拉雅", "钉钉", "UC浏览器", "三星浏览器", "诺基亚浏览器", "欧朋", "火狐", "知乎", "飞书", "Iphone", "Ipad", "苹果电脑", "其他浏览器", "抖音APP", "抖音极速版", "抖音火山版", "今日头条", "今日头条极速版", "西瓜视频", "番茄小说", "百度极速版", "百度贴吧", "API调用"];
        try {
            return browsers[key];
        } catch (e) {
            return '-----';
        }
    }
}

function getLinkUrl(links_id,links_day) {
    var linkUrl = "https://s.pdb2.com/pages/"+links_day+"/"+links_id+".html";
    copyWailianPath(linkUrl, "通用链接")
}

function qrcodesListsAllImagesAdd(){
    $("#addallqrcodeModal").modal('toggle');
}
function jsUploadaa(max){
    $.each($("#upload_multiple_qrcode")['0'].files,function(index,val){
        console.log(imagearr.length+index);
        if(imagearr.length+index < 10){
            uploadEach(index,val,max);
        }
    })
}
function uploadEach(index,val,max){
    var reader = new FileReader();
    reader.readAsDataURL(val);
    reader.onload = function (e) {
        var data = e.target.result;
        //加载图片获取图片真实宽度和高度
        var image = new Image();
        image.src = data;
        // 图片先加载完，才可以得到图片宽度和高度
        image.onload = function(){
            var width = image.width;
            var height = image.height;
            var pressParamas = {};
            if (width > 800) {
                pressParamas.width = 800;
            }
            if (val.size >= 1000000) {
                pressParamas.size = 300;
                pressParamas.quality = 0.8;
            } else if (val.size >= 500000) {
                pressParamas.size = 200;
                pressParamas.quality = 0.8;
            } else {
                pressParamas.size = 100;
                pressParamas.quality = 0.8;
            }
            var origin_type = val.type;
            if ($.inArray(origin_type,["image/png","image/webp"]) < 0) {
                pressParamas.type = val.type;
            } else {
                pressParamas.type = "image/jpeg";
            }
            imageConversion.compress(val,pressParamas).then(pressResult=>{
                var pressFile = blobToFile(pressResult,val.name,val.type);
                var oldSize = (val.size/1024).toFixed(0);
                var resultSize = (pressFile.size/1024).toFixed(0);
                if (resultSize > max) {
                    mviewToastr("error","图片压缩后不能超过"+max+"KB,当前为"+resultSize+"KB。");
                    return;
                }
                aliOssUploads(pressFile,'uploads',index);
            });
        }
    }
}

function aliOssUploads(file,dir,index){
    var randomId = generateRandomInteger(10000,99999);
    //获取上传的文件名，并得到文件后缀
    var point = file.name.lastIndexOf(".");
    var file_type = file.name.substr(point);//获取文件后缀
    var file_name_a = file.name.substr(0,point);//获取文件名称
    var day = getCurrentTime("day");
    var time = getCurrentTime("time");
    var imageName = randomId+file_type;
    var file_name = dir+"/"+day+"/"+time+randomId+file_type;
    //发送ajax请求我方php后端获取上传OSS时必要的参数信息
    $.ajax({
        type : "get", //提交方式
        url : "/api/version/1/oss/alioss_access_token",//路径
        data : {
            "dir" : dir
        },//数据，这里使用的是Json格式进行传输
        success : function(res) {//返回数据根据结果进行相应的处理
            res = JSON.parse(res);
            var imageurl = res.host+file_name;
            //上返回的参数使用formData中
            let formData = new FormData();
            formData.append('key', file_name);
            formData.append('OSSAccessKeyId', res.accessid);
            formData.append('policy', res.policy);
            formData.append('Signature', res.signature);
            formData.append('callback', res.callback);
            formData.append('success_action_status', 200); // 成功后返回的操作码
            formData.append('file', file);
            //接收到服务端返回的签名参数，开始通过另一个Ajax请求来上传文件到OSS
            //成功获取签名后上传文件到阿里云OSS
            $.ajax({
                type : "POST", //提交方式
                url : res.host,//路径
                dataType:'JSON',
                processData: false,
                cache: false,
                async: false,
                contentType: false,
                data : formData,
                success : function(result) {
                    if (result.Status == "Ok") {
                        if(imagearr.length < 30){
                            imagearr.push({"image":imageurl,"id":randomId,"name":file_name_a});
                            $("#image_arr").append('<div id="qrcode-item-'+randomId+'"><img src="'+imageurl+'" alt="'+file_name_a+'"><div onclick="deleteqrcode('+randomId+')"><icon class="iconfont icon-shanchu1"></icon></div></div>');
                        }
                    }
                },error:function(err){
                    mviewToastr("error","图片上传失败,请联系客服处理！");
                }
            });
        },error:function(err){
            mviewToastr("error","网络异常,请联系客服处理！");
        }
    });
}
function qrcodesImagesAddAllSubmit(){
    if (imagearr.length == 0) {
        mviewToastr("error", "请上传二维码!");
        return;
    }
    var qrcodes_name = $("#qrcodes_name").val();
    var expiration_time = $("#all_expiration_time").val();
    if (expiration_time == "") {
        mviewToastr("error", "请选择二维码有效期!");
        return;
    }
    var rate = $("#all_rate").val();
    if (rate == "") {
        mviewToastr("error", "请输入二维码权重!");
        return;
    }
    var count_limit = $("#all_count_limit").val();
    if (count_limit == "") {
        mviewToastr("error", "请输入二维码访问上限!");
        return;
    }
    var users_id = $("#users_id").val();
    var links_id = $("#links_id").val();
    $.ajax({
        "url": "/api/version/1/links/qrcodes_add",
        "type": "POST",
        data: {
            "links_id": links_id,
            "users_id": users_id,
            "qrcode": imagearr,
            "expiration_time": expiration_time,
            "rate": rate,
            "count_limit": count_limit,
            "multiple":1,
        },
        success: function(res) {
            if (res.status == "success") {
                qrcodeListReload();
                $("#addallqrcodeModal").modal('toggle');
                mviewToastr("success", res.msg);
                imagearr = [];
                $("#image_arr").empty();
            } else {
                mviewToastr("error", res.msg);
            }
        },
        error: function(err) {
            mviewToastr("error", "网络异常,请稍后重试！");
        }
    });
}
function deleteqrcode(id){
    imagearr = imagearr.filter(item=>item.id != id);
    $("#qrcode-item-"+id).remove();
}
